import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:bot_toast/bot_toast.dart';
import '../controllers/home_controller.dart';
import '../../tabbar/controllers/tabbar_controller.dart';
import '../../message/controllers/message_controller.dart';
import '../../device/controllers/device_controller.dart';
import '../../../widgets/safe_network_image.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      body: const SingleChildScrollView(
        child: Column(
          children: [
            HomeTopBackground(),
            HomeMenuSection(),
            HomeDeviceStatsSection(),
            HomeBottomSection(),
          ],
        ),
      ),
    );
  }
}

/// 顶部背景组件（只包含背景和标题）
class HomeTopBackground extends GetView<HomeController> {
  const HomeTopBackground({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: Get.width,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/home/top_bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.only(
              left: 20.w,
              top: 80.h,
              right: 20.w,
              bottom: 10,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 30.h),
                Text(
                  '华数灵眸',
                  style: TextStyle(
                    fontSize: 46.sp,
                    fontWeight: FontWeight.bold,
                    color: const Color(0xFF333333),
                  ),
                ),
                SizedBox(height: 6.h),
                Text(
                  '一眼安心，时刻守护',
                  style: TextStyle(
                    fontSize: 26.sp,
                    color: const Color(0xFF333333),
                  ),
                ),
              ],
            ),
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(16.r),
            child: SizedBox(
              height: 320.h,
              child: Obx(() {
                final bannerList = controller.bannerList;

                // 如果没有banner数据，显示默认banner
                if (bannerList.isEmpty) {
                  return Container(
                    decoration: const BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/images/home/banner.png'),
                        fit: BoxFit.fill,
                      ),
                    ),
                  );
                }

                // 显示真实banner数据
                return Swiper(
                  itemBuilder: (BuildContext context, int index) {
                    final banner = bannerList[index];
                    final imageUrl = banner['imageUrl']?.toString() ?? '';

                    return GestureDetector(
                      onTap: () => controller.onBannerTap(banner),
                      child:
                          imageUrl.isNotEmpty
                              ? SafeNetworkImage(
                                imageUrl: imageUrl,
                                fit: BoxFit.fill,
                                borderRadius: BorderRadius.circular(16.r),
                                errorWidget: Container(
                                  decoration: const BoxDecoration(
                                    image: DecorationImage(
                                      image: AssetImage(
                                        'assets/images/home/banner.png',
                                      ),
                                      fit: BoxFit.fill,
                                    ),
                                  ),
                                ),
                              )
                              : Container(
                                decoration: const BoxDecoration(
                                  image: DecorationImage(
                                    image: AssetImage(
                                      'assets/images/home/banner.png',
                                    ),
                                    fit: BoxFit.fill,
                                  ),
                                ),
                              ),
                    );
                  },
                  itemCount: bannerList.length,
                  autoplay: bannerList.length > 1,
                  autoplayDelay: 3000,
                  duration: 300,
                  curve: Curves.easeInOut,
                  scrollDirection: Axis.horizontal,
                  loop: bannerList.length > 1,
                  pagination:
                      bannerList.length > 1
                          ? SwiperPagination(
                            alignment: const Alignment(0.0, 0.8),
                            builder: SwiperCustomPagination(
                              builder: (
                                BuildContext context,
                                SwiperPluginConfig config,
                              ) {
                                return Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: List.generate(
                                    bannerList.length,
                                    (index) => AnimatedContainer(
                                      duration: const Duration(
                                        milliseconds: 200,
                                      ),
                                      margin: EdgeInsets.symmetric(
                                        horizontal: 4.w,
                                      ),
                                      width: 12.w,
                                      height: 12.h,
                                      decoration: BoxDecoration(
                                        color:
                                            config.activeIndex == index
                                                ? Colors.white
                                                : Colors.white.withValues(
                                                  alpha: 0.5,
                                                ),
                                        shape: BoxShape.circle,
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.black.withValues(
                                              alpha: 0.2,
                                            ),
                                            blurRadius: 4.r,
                                            offset: const Offset(0, 1),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          )
                          : null,
                );
              }),
            ),
          ),
        ],
      ),
    );
  }
}

/// 菜单区域组件
class HomeMenuSection extends StatelessWidget {
  const HomeMenuSection({super.key});

  static const List<MenuItemData> _menuItems = [
    MenuItemData(
      iconPath: 'assets/images/home/alert_icon.png',
      label: '告警消息',
      route: '/message',
    ),
    MenuItemData(
      iconPath: 'assets/images/home/device_icon.png',
      label: '设备列表',
      route: '/device',
    ),
    MenuItemData(
      iconPath: 'assets/images/home/order_icon.png',
      label: '订单列表',
      route: '/order-list',
    ),
    MenuItemData(iconPath: 'assets/images/home/more_icon.png', label: '更多'),
  ];

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 710.w,
      decoration: BoxDecoration(
        // 白色边框
        border: Border.all(color: Colors.white, width: 4.w),
        // 主背景渐变
        gradient: const LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: [0.0, 0.96],
          colors: [
            Color.fromRGBO(234, 244, 254, 0.71), // rgba(234,244,254,0.71)
            Color(0xFFFFFFFF), // #FFFFFF
          ],
        ),
        borderRadius: BorderRadius.circular(20.r),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFD6E9FF), // #D6E9FF
            blurRadius: 19.r,
            spreadRadius: 0,
            offset: const Offset(0, 0),
          ),
        ],
      ),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 60.w, vertical: 24.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: _menuItems.map((item) => _buildMenuItem(item)).toList(),
        ),
      ),
    );
  }

  /// 优化的切换到消息tab方法
  void _switchToMessageTab() {
    try {
      // 检查当前是否在TabBar页面
      if (Get.currentRoute == '/tabbar') {
        // 已在TabBar页面，直接切换tab
        _switchTabWithFeedback();
      } else {
        // 不在TabBar页面，先跳转再切换
        Get.offAllNamed('/tabbar');
        // 页面跳转后切换tab
        Future.delayed(const Duration(milliseconds: 150), () {
          _switchTabWithFeedback();
        });
      }
    } catch (e) {
      print('切换到消息tab失败: $e');
      // 降级处理：直接跳转到TabBar页面
      Get.offAllNamed('/tabbar');
      BotToast.showText(text: '正在跳转到消息页面...');
    }
  }

  /// 切换tab并提供用户反馈
  void _switchTabWithFeedback() {
    try {
      final tabController = Get.find<TabbarController>();
      tabController.changeTabIndex(2); // 消息tab是索引2

      // 确保消息页面数据更新
      try {
        final messageController = Get.find<MessageController>();
        messageController.refreshData();
        print('消息页面数据已刷新');
      } catch (e) {
        print('消息Controller未找到或刷新失败: $e');
      }

      print('成功切换到消息tab');
    } catch (e) {
      print('TabController未找到: $e');
      BotToast.showText(text: '页面切换中，请稍候...');
      // 延迟重试一次
      Future.delayed(const Duration(milliseconds: 300), () {
        try {
          final tabController = Get.find<TabbarController>();
          tabController.changeTabIndex(2);

          // 延迟刷新消息数据
          try {
            final messageController = Get.find<MessageController>();
            messageController.refreshData();
          } catch (e) {
            print('延迟刷新消息数据失败: $e');
          }

          BotToast.showText(text: '已切换到消息页面');
        } catch (e) {
          print('延迟重试仍失败: $e');
        }
      });
    }
  }

  Widget _buildMenuItem(MenuItemData item) {
    return GestureDetector(
      onTap: () {
        if (item.label == '告警消息') {
          // 优化的切换到消息tab逻辑
          _switchToMessageTab();
        } else if (item.label == "设备列表") {
          final tabController = Get.find<TabbarController>();
          tabController.changeTabIndex(1); // 消息tab是索引2
        } else if (item.label == '更多') {
          // 显示敬请期待提示
          BotToast.showText(text: '敬请期待');
        } else if (item.route != null) {
          Get.toNamed(item.route!);
        }
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 图标
          Container(
            width: 74.w,
            height: 74.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(item.iconPath),
                fit: BoxFit.contain,
              ),
            ),
          ),
          SizedBox(height: 12.h),
          // 文本标签
          Text(
            item.label,
            style: TextStyle(
              fontSize: 24.sp,
              color: const Color(0xFF333333),
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
}

/// 菜单项数据模型
class MenuItemData {
  final String iconPath;
  final String label;
  final String? route;

  const MenuItemData({required this.iconPath, required this.label, this.route});
}

/// 设备统计区域组件
class HomeDeviceStatsSection extends GetView<HomeController> {
  const HomeDeviceStatsSection({super.key});

  /// 跳转到设备列表并设置状态筛选
  void _navigateToDeviceWithStatus(int statusIndex) {
    try {
      // 检查当前是否在TabBar页面
      if (Get.currentRoute == '/tabbar') {
        // 已在TabBar页面，直接切换tab
        _switchToDeviceTabWithStatus(statusIndex);
      } else {
        // 不在TabBar页面，先跳转再切换
        Get.offAllNamed('/tabbar');
        // 页面跳转后切换tab并设置状态
        Future.delayed(const Duration(milliseconds: 150), () {
          _switchToDeviceTabWithStatus(statusIndex);
        });
      }
    } catch (e) {
      print('跳转到设备列表失败: $e');
      // 降级处理：直接跳转到TabBar页面
      Get.offAllNamed('/tabbar');
      BotToast.showText(text: '正在跳转到设备列表...');
    }
  }

  /// 切换到设备tab并设置状态筛选
  void _switchToDeviceTabWithStatus(int statusIndex) {
    try {
      final tabController = Get.find<TabbarController>();
      tabController.changeTabIndex(1); // 设备tab是索引1

      // 延迟设置状态筛选，确保DeviceController已初始化
      Future.delayed(const Duration(milliseconds: 200), () {
        try {
          final deviceController = Get.find<DeviceController>();
          deviceController.changeStatus(statusIndex); // 1=在线, 2=离线
          print('成功切换到设备列表并设置状态: $statusIndex');
        } catch (e) {
          print('设置设备状态筛选失败: $e');
        }
      });
    } catch (e) {
      print('TabController未找到: $e');
      BotToast.showText(text: '页面切换中，请稍候...');
    }
  }

  /// 跳转到未读消息页面
  void _navigateToUnreadMessages() {
    try {
      // 检查当前是否在TabBar页面
      if (Get.currentRoute == '/tabbar') {
        // 已在TabBar页面，直接切换tab
        _switchToUnreadMessagesTab();
      } else {
        // 不在TabBar页面，先跳转再切换
        Get.offAllNamed('/tabbar');
        // 页面跳转后切换tab
        Future.delayed(const Duration(milliseconds: 150), () {
          _switchToUnreadMessagesTab();
        });
      }
    } catch (e) {
      print('跳转到未读消息页面失败: $e');
      // 降级处理：直接跳转到TabBar页面
      Get.offAllNamed('/tabbar');
      BotToast.showText(text: '正在跳转到消息页面...');
    }
  }

  /// 切换到未读消息tab
  void _switchToUnreadMessagesTab() {
    try {
      final tabController = Get.find<TabbarController>();
      tabController.changeTabIndex(2); // 消息tab是索引2

      // 延迟切换到未读消息tab，确保MessageController已初始化
      Future.delayed(const Duration(milliseconds: 200), () {
        try {
          final messageController = Get.find<MessageController>();
          messageController.changeTab(1); // 1=未读消息tab
          print('成功切换到未读消息tab');
        } catch (e) {
          print('切换到未读消息tab失败: $e');
        }
      });
    } catch (e) {
      print('TabController未找到: $e');
      BotToast.showText(text: '页面切换中，请稍候...');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: 710.w,
        margin: EdgeInsets.only(top: 20.h),
        decoration: BoxDecoration(
          // 白色边框
          border: Border.all(color: Colors.white, width: 4.w),
          // 主背景渐变
          gradient: const LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            stops: [0.0, 0.96],
            colors: [
              Color.fromRGBO(234, 244, 254, 0.71), // rgba(234,244,254,0.71)
              Color(0xFFFFFFFF), // #FFFFFF
            ],
          ),
          borderRadius: BorderRadius.circular(20.r),
          boxShadow: [
            BoxShadow(
              color: const Color(0xFFD6E9FF), // #D6E9FF
              blurRadius: 19.r,
              spreadRadius: 0,
              offset: const Offset(0, 0),
            ),
          ],
        ),
        child: Padding(
          padding: EdgeInsets.all(40.w),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '我的设备',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: const Color(0xFF333333),
                ),
              ),
              SizedBox(height: 30.h),
              Obx(
                () => Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 在线通道
                    GestureDetector(
                      onTap: () => _navigateToDeviceWithStatus(1),
                      child: Column(
                        children: [
                          Text(
                            '${controller.onlineChannels}',
                            style: TextStyle(
                              fontSize: 48.sp,
                              fontWeight: FontWeight.bold,
                              color: const Color(0xFF047FF7),
                            ),
                          ),
                          SizedBox(height: 8.h),
                          Text(
                            '在线通道',
                            style: TextStyle(
                              fontSize: 24.sp,
                              fontWeight: FontWeight.w500,
                              color: const Color(0xFF666666),
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                    // 离线通道
                    GestureDetector(
                      onTap: () => _navigateToDeviceWithStatus(2),
                      child: Column(
                        children: [
                          Text(
                            '${controller.offlineChannels}',
                            style: TextStyle(
                              fontSize: 48.sp,
                              fontWeight: FontWeight.bold,
                              color: const Color(0xFF047FF7),
                            ),
                          ),
                          SizedBox(height: 8.h),
                          Text(
                            '离线通道',
                            style: TextStyle(
                              fontSize: 24.sp,
                              fontWeight: FontWeight.w500,
                              color: const Color(0xFF666666),
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                    // 未读消息
                    GestureDetector(
                      onTap: () => _navigateToUnreadMessages(),
                      child: Column(
                        children: [
                          Text(
                            '${controller.unreadCount}',
                            style: TextStyle(
                              fontSize: 48.sp,
                              fontWeight: FontWeight.bold,
                              color: const Color(0xFF047FF7),
                            ),
                          ),
                          SizedBox(height: 8.h),
                          Text(
                            '未读消息',
                            style: TextStyle(
                              fontSize: 24.sp,
                              fontWeight: FontWeight.w500,
                              color: const Color(0xFF666666),
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// 底部图片区域组件
class HomeBottomSection extends StatelessWidget {
  const HomeBottomSection({super.key});

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: GestureDetector(
            onTap: () {
              Get.toNamed('/download');
            },
            child: Container(
              height: 446.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/home/bottom_left.png'),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          ),
        ),
        Expanded(
          child: Container(
            height: 446.h,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home/bottom_right.png'),
                fit: BoxFit.fill,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
